using System;
using System.Collections.Generic;
using cfg.level;
using QAssetBundle;
using UnityEngine;
using QFramework;
using Unity.VisualScripting;
using Random = UnityEngine.Random;

namespace QFramework.Monk
{
	public partial class Player : ViewController
	{
		public static Player Default;
		private List<AbilityBase> mAbilities = new List<AbilityBase>();
		//public float Speed = 5;
		private bool mIsFaceLeft = true;
		private AudioPlayer mAudioPlayer;
		void Start()
		{
			Default = this;
			HurtBox.OnCollisionEnter2DEvent((collision) =>
			{
				if (collision.gameObject.layer== LayerMask.NameToLayer("Enemy"))
				{
					AppStart.curHp.Value--;
					if (AppStart.curHp.Value == 0)
					{
						AudioKit.PlaySound("die");
						this.gameObject.DestroySelfGracefully();
						AppStart.ChangeGameState(GameState.GameOver);
						
					}
					else
					{
						AudioKit.PlaySound("hurt");
					}
				}
				//UIKit.OpenPanel<UIGameOver>();
			}).UnRegisterWhenGameObjectDestroyed((this.gameObject));
			
			AppStart.curHp.RegisterWithInitValue((num =>
			{
				if (num<0)
				{
					num = 0;//防止显示负值
				}
				HpBar.fillAmount = (float)num/AppStart.maxHp.Value;
				
			})).UnRegisterWhenGameObjectDestroyed(this.gameObject);
		}

		private void OnDestroy()
		{
			Default = null;
		}

		public void InitAbility()
		{
			mAbilities.Clear();
			
			mAbilities.Add(SimpleAxe);
			mAbilities.Add(SimpleSword);
			mAbilities.Add(SimpleBall);
			mAbilities.Add(SimpleCircle);
			mAbilities.Add(SimpleKnife);
			
			var random = Random.Range(0, mAbilities.Count);
			
			for (var i = 0; i < mAbilities.Count; i++)
			{
				mAbilities[i].InitAbility();
				if (random == i)//随机解锁一个能力
				{
					mAbilities[i].UnLockAbility(true);
				}
			}
			
		}
		

		void Update()
		{
			if (!AppStart.CheckGameState(GameState.GamePlaying))
			{
				if (mAudioPlayer!=null)
				{
					mAudioPlayer.Stop();
					mAudioPlayer = null;
				}
				return;
			}
			// Code Here	
			var horizontal = Input.GetAxisRaw("Horizontal");
			var vertical = Input.GetAxisRaw("Vertical");
			//平方后的归一化
			var direction = new Vector2(horizontal, vertical).normalized;
			var targetSpeed = direction * AppStart.playerSpeed.Value;
			SelfRigidbody2D.velocity = Vector2.Lerp(SelfRigidbody2D.velocity, targetSpeed, 1f-Mathf.Exp(-Time.fixedDeltaTime * 5));
			
			if (horizontal==0&&vertical==0)
			{
				if (mIsFaceLeft)
				{
					SelfAnimator.Play("idle_left");
				}
				else
				{
					SelfAnimator.Play("idle_right");
				}

				if (mAudioPlayer!=null)
				{
					mAudioPlayer.Stop();
					mAudioPlayer = null;
				}
			}
			else
			{
					mIsFaceLeft = direction.x<0!;
					
					if (mIsFaceLeft)
					{
						SelfAnimator.Play("work_left");
					}
					else
					{
						SelfAnimator.Play("work_right");
					}

					if (mAudioPlayer==null)
					{
						mAudioPlayer = AudioKit.PlaySound(Sxf.WALK,true);
					}
			}
		}
		
	}
}
